import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from './pubulic.decorator';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    readonly reflector: Reflector,
    private readonly jwtService: JwtService,
  ) {}
 async canActivate(
    context: ExecutionContext,
  ):  Promise<boolean>  {
    const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) return true;
    const request = context.switchToHttp().getRequest();
    const token = extractToken(request);
    if (!token) {
      throw new UnauthorizedException('请先登录');
    }
    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: 'abcdefg',
      });
      request.user = payload;
      console.log(payload,'payload');
      
    } catch (error) {
      throw new UnauthorizedException('登录失败');
    }

    return true;
  }
}
function extractToken(request) {
  const [type, token] = request.headers?.authorization?.split(' ') ?? [];
  if (type === 'Bearer') {
    return token;
  }
}
